const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return `${[year, month, day].map(formatNumber).join('-')}`
}

const formatMonth = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1

  return `${[year, month].map(formatNumber).join('-')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

// 获得UUID
function getUUID(n = 32) {
  var str = "abcdefghijklmnopqrstuvwxyz0123456789"; // 可以作为常量放到random外面
  var result = "";
  for (var i = 0; i < n; i++) {
    result += str[parseInt(Math.random() * str.length)];
  }
  return result;
}

// 获得秒级时间戳
function getCurTimeSeconds() {
  return parseInt(new Date().getTime()/1000)+"";
}

// 不属于，中文字符串 true：不属于中文
function isNotChineseStr(val) {
  if(!val){
    return true;
  }
  let chinese = /[^\u4E00-\u9FA5]/g;
  return chinese.test(val);
}

// 是否属于中国手机号 true：是中国手机号
function isChinaCellPhoneNumber(val){
  if(!val){
    return false;
  }
  let phoneValReg = /^((13[0-9])|(14(0|[5-7]|9))|(15([0-3]|[5-9]))|(16(2|[5-7]))|(17[0-8])|(18[0-9])|(19([0-3]|[5-9])))\d{8}$/;
  return phoneValReg.test(val);
}

// 短信验证码
function isSmsCode(val){
  if(!val){
    return false;
  }
  let smsCodeValReg = /^\d{6}$/;
  return smsCodeValReg.test(val);
}

// 算术图形验证码
function isCaptchaResult(val){
  if(!val){
    return false;
  }
  let captchaReg = /^-?\d{1,2}$/;
  return captchaReg.test(val);
}

module.exports = {
  formatTime: formatTime,
  formatDate: formatDate,
  formatMonth: formatMonth,
  getUUID,
  getCurTimeSeconds,
  isNotChineseStr,
  isChinaCellPhoneNumber,
  isSmsCode,
  isCaptchaResult,
}